package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.oss.service.FileService;
import com.atguigu.yygh.oss.utils.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Author zhmwi
 * @Date 2021/7/19
 * @Dersciption
 */
@Service
public class FileServiceImpl implements FileService {

    //上传文件
    @Override
    public String upload(MultipartFile file) {
        //1.初始化参数,创建客户端对象
        //1.1获取参数
        String endPoint = OssProperties.END_POINT;
        String accessKeyId = OssProperties.ACCESS_KEY_ID;
        String accessKeySecret = OssProperties.ACCESS_KEY_SECRET;
        String bucketName = OssProperties.BUCKET_NAME;
        try {
            //1.2创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            //2.获取文件输入流
            InputStream inputStream = file.getInputStream();
            //3.整理文件及文件夹
            //设置文件名唯一   asdsadfgzsdafs.jpg
            String fileName = UUID.randomUUID().toString().replace("-","")+ file.getOriginalFilename();
            //按照当前日期 创建文件夹 上传到创建文件夹里面
            //2021/07/19/zsdsdsfsfg.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl + "/" + fileName;
            //4.客户端对象调用方法上传文件
            ossClient.putObject(bucketName,fileName,inputStream);

            //关闭ossClient
            ossClient.shutdown();
            //上传之后文件路径
            // https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endPoint+"/"+fileName;
            //返回
            return url;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
